package cn.meye11.crm.service;


import cn.meye11.crm.common.DateUtils;
import cn.meye11.crm.common.RestResponse;
import cn.meye11.crm.common.StringUtils;
import cn.meye11.crm.domain.entity.ConsumptionRecordsEntity;
import cn.meye11.crm.domain.entity.MemberEntity;
import cn.meye11.crm.domain.model.Member;
import cn.meye11.crm.domain.query.MemberQuery;
import cn.meye11.crm.mapper.ConsumptionRecordsMapper;
import cn.meye11.crm.mapper.MemberMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员信息表(Member)表服务实现类
 * 默认CRUD操作
 *
 * @author makejava
 * @since 2023-11-11 13:34:00
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class MemberService {
    private final MemberMapper memberMapper;
    private final ConsumptionRecordsMapper consumptionRecordsMapper;

    // 代码写到此区域
    @Transactional(rollbackFor = Exception.class)
    public RestResponse<String> refund(Long id) {
        MemberEntity entity = memberMapper.selectByPrimaryKey(id);
        if (entity == null) {
            throw new RuntimeException("ID:" + id + "会员，不存在");
        }

        if (entity.getDel() == 1) {
            throw new RuntimeException("ID:" + id + "会员，已删除");
        } else {
            //同时生成一条类型为【会员退费】的消费记录
            ConsumptionRecordsEntity recordsEntity = ConsumptionRecordsEntity.builder()
                    .memberId(id)
                    .memberName(entity.getName())
                    .amount(entity.getRechargeBalance())
                    .fitEntryChannels("会员退费")
                    .items("会员退费")
                    .operators("会员退费")
                    .consumptionTime(LocalDateTime.now())
                    .label("会员退费")
                    .createdBy("会员退费")
                    .modifiedBy("会员退费")
                    .build();

            consumptionRecordsMapper.insertSelective(recordsEntity);

            entity.setModifiedBy("会员退费");
            entity.setLast(LocalDateTime.now());
            entity.setRechargeBalance(0d);
            entity.setGiftBalance(0d);
            memberMapper.updateByPrimaryKey(entity);
        }
        return RestResponse.success("退费完成");
    }

    /************************************* 请在上方编写新代码 **************************************/
    // 此区域为自动生成的通用代码 尽量不直接修改
    @Transactional(rollbackFor = Exception.class)
    public Long save(Member model) {

//        if (StringUtils.isBlank(model.getCreatedBy())) {
//            throw new RuntimeException("创建人不能为空");
//        }
        if (model.getId() != null) {
            throw new RuntimeException("主键id不可自定义");
        }
        if (model.getVersion() != null) {
            throw new RuntimeException("数据版本号不可自定义");
        }
        if (model.getTime() != null) {
            throw new RuntimeException("数据创建时间不可自定义");
        }
        if (model.getLast() != null) {
            throw new RuntimeException("数据修改时间不可自定义");
        }

        model.setRegistrationDate(new Date());
        model.setGiftBalance(0d);
        model.setRechargeBalance(0d);
        model.setRegistrationDate(new Date());
        MemberEntity entity = new MemberEntity(model);
        entity.setTime(DateUtils.toLocalDateTime(new Date()));
        entity.setLast(DateUtils.toLocalDateTime(new Date()));

        memberMapper.insert(entity);

        return entity.getId();
    }

    public void remove(Long id) {
        if (id == null) {
            throw new RuntimeException("ID不能为空");
        }

        MemberEntity entity = memberMapper.selectByPrimaryKey(id);
        if (entity == null) {
            throw new RuntimeException("ID:" + id + "不存在");
        }
        memberMapper.deleteByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(Member model) {

        if (model.getId() == null) {
            throw new RuntimeException("ID不能为空");
        }

        if (StringUtils.isBlank(model.getModifiedBy())) {
            throw new RuntimeException("修改人不能为空");
        }

        MemberEntity entity = memberMapper.selectByPrimaryKey(model.getId());
        if (entity == null) {
            throw new RuntimeException("ID:" + model.getId() + "不存在");
        }

        MemberEntity save = new MemberEntity(model);
        save.setLast(LocalDateTime.now());
        save.setTime(entity.getTime() == null ? DateUtils.toLocalDateTime(new Date()) : entity.getTime());
        memberMapper.updateByPrimaryKeySelective(save);
    }

    public Member get(Long id) {
        MemberEntity entity = memberMapper.selectByPrimaryKey(id);
        return entity == null ? null : new Member(entity);
    }

    public Long count(MemberQuery query) {
        return memberMapper.count(query);
    }

    public RestResponse<List<Member>> list(MemberQuery query) {
        // 单次查不得大于32767条数据，否则需要分页
        query.setLimit((int) Short.MAX_VALUE);
        return page(query);
    }

    public RestResponse<List<Member>> page(MemberQuery query) {
        PageHelper.startPage(query.getPage(), query.getLimit());
        List<MemberEntity> list = memberMapper.list(query);
        PageInfo<MemberEntity> count = new PageInfo<>(list);
        List<Member> collect = list.stream().map(Member::new).collect(Collectors.toList());
        return RestResponse.success(count.getTotal(), collect);
    }

}
